import numpy as np
from numpy import *

import matplotlib
import matplotlib.pyplot as plt

# 解决可视化界面中文显示问题
import matplotlib.font_manager as fm
import math

myfont = fm.FontProperties(fname='C:\Windows\Fonts\simsun.ttc')


def base_dataset():
    dataset = array([[8, 4, 2], [7, 1, 1], [1, 4, 4], [3, 0, 5]])
    labels = ['非常热', '非常热', '一般热', '一般热']
    return dataset, labels

# 可视化分析数据


def analyze_data_plot(x, y):
    fig = plt.figure()
    # 将画布划分为1行1列1块
    ax = fig.add_subplot(111)
    ax.scatter(x, y)

    plt.title('冷热感知散点图', fontsize=25, fontname='宋体', fontproperties=myfont)
    plt.xlabel('吃冰淇淋量', fontsize=15, fontname='宋体', fontproperties=myfont)
    plt.ylabel('喝水量', fontsize=15, fontname='宋体', fontproperties=myfont)
    plt.show()


def euclidean_distance(arr1, arr2, len):
    v = 0
    for i in range(len):
        v += math.pow((arr1[i] - arr2[i]), 2)
    return math.sqrt(v)


def euclidean_distance2(newV, datasets):
    rowsize, colsize = datasets.shape
    # 向量与数组datasets里的每一项进行求差值
    diffV = tile(newV, (rowsize, 1)) - datasets
    # 求出差值后，每一项差值进行平方
    sqV = diffV**2

    # 平方后再每项求和后开方
    result = sqV.sum(axis=1)**0.5

    return result

# knn投票分析器


def knn_analyze(newV, datasets, labels, k):
    import operator
    # 传入需要进行分析的向量，及基础的数据集和标签
    # 求欧氏距离
    ecList = euclidean_distance2(newV, datasets)
    # 排序
    sortIndexs = ecList.argsort(axis=0)
    listContainer = {}
    for i in range(k):
        label = labels[sortIndexs[i]]

        listContainer[label] = listContainer.get(label, 0) + 1

    # operator.itemgetter 1按值排序，0按键排序
    result = sorted(
        listContainer.items(), key=operator.itemgetter(1), reverse=True)[0][0]
    return result


if __name__ == '__main__':
    dataset, labels = base_dataset()

    # analyze_data_plot(dataset[:,0],dataset[:,1])

    # newV = [2,5,1]
    # for x in dataset:
    # 	print(euclidean_distance(newV,x,3))

    # newV = [2,6,2]
    # arr = euclidean_distance2(newV,dataset)
    # for x in arr:
    # 	print(x)

    # newV = [2,7,3]
    # print(knn_analyze(newV,dataset,labels,3))

    iceNum = float(input('Q：吃冰淇淋数目\n'))
    waterNum = float(input('Q：喝水量\n'))
    actionTime = float(input('Q：活动时间\n'))
    newV = array([iceNum, waterNum, actionTime])
    res = knn_analyze(newV, dataset, labels, 3)
    print('当天天气评估:', res)
